package com.example.shunsu.test;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64EncoderStream;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * 云医签
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class Yyq {

    //云平台测试
    private static String SIGN_ALGORITHMS = "SHA256WithRSA";

    private static String privatekey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDSQxMHYg9ydQWSuYPRT6FqF2Pg1kfmOHF+m9loeCfpzaHgtFyfJf2/lGyxOm19d9TdVpqw8yvHjWORWkV2QzQIgfkpb8N0ZG4oy8dOZPUPiTvdVOZq6rn8SKZNjbJpSkngmEREfBpqHAHkN/HvTpNjVzimOQc2brsHCi0w36qtGHcLM7H9qxjP5P/rMgrXZFXKk7ggtrHk4tGrzaLr0/NtmjqVr5PVmslhOYMJpf91NgLbLDyP68+NGh9wojVvCje5bKkHp76Rdc9pzEMI4t873N4U8J81Jy12dcCXmiAGJXNBfcXElWCzogzlPMsYzmmE/V9TIieSn18guhwluy2RAgMBAAECggEBAKLqzee+l3F8MuFJVVXteYiWrxEbd4Ju4aHUaFSGJYcHihJuLgYyjbbP7pg0SXoaS5lk7V+GS7nHWArcA05rK/obm0/8BVo+Jwz9OGUJ3Mg48WXBzvexAIL2V8VnsYHbyfp4gQz/jAgDw4NtxcxC+fjTMFW7glcu3UPLItDnvXt4PcaegTZFQUqnL0HNh1UCAQbEmC0N+SxZ73TL0ilKGZMkk3oOtpqqOEyeSOspBB5o+ctNnrBgFJ165RjU2+g5peY0hetY/FY0y0TacQt4lvUdsoUn07G+NoCnYQ4jELORFhUOhCiJUW+B93S4+o9OpUA6bzVp9hxFgERyDfsfFfECgYEA7QpqQG5MW7hGGJc18GuXP3OSw8Qppgy9Bnxkah8PCmM7WLl9vtNp4dIPfykdBYUFj7adGCTFNbPcI1Pff8zqb9cZEaRr4xvJAIxl4Bpp2b1LyAMAm8cAs6w7Ywkt8vyI7Xa/wr2DmTE64k1trS+EEkSr5+tzWkAb82I5y4KTg6cCgYEA4xRYjvUSb1W6UafEpIBITtG+Ejfb9mWSfHxn/z3/J12VHTGVi/Zj3iXY5u6znBIz6s2RiCq1U6pCWQQMTz98u5BSXFLim1FKeVrrypJ4SIQCEywKOWKQ07FvaXyTV9C3O8YpYvWUHmC60VjzhN/d+BN9+W6xyfaul6JrVKobTAcCgYEAhvFf7ZAdHjX4ibVDerv1XaTwz0vUHfiwf4m/LH7D9DjrpyXqBQGcDHemZNDF+cdxlA/0vLLqJhlfYCk2Wi4Q5FyCo/2DgcXmls5WjM7cpZ1TD+lNpmES8DZDlKy8INFNLkpk/nse+M4C5KQJpQcg27mGV8A9agqHHvYzSrzqN48CgYASimu8qGfr7Tz8Q817fPnqbZeuVx8/nAV84o9/OKmnpi1xp8XFGsYGsmJmYKELojTY/BXg31PU0/b826bBpbZifiMrZJ0Z/2YsSG8uKA1oJlchB5yCGPkoP7mQDFrfdawwVjq02MZSQKWgSDoB5GF0SusjPZWInvqcaOeIjycRawKBgBTGxaWaOnoe2xRCMiucVFX0eu/zq0UBf/+cDZRFnvBvRFOknAkKcYLS7VfpxDyxHnKPfhbTJR7xrpbx/ju+E1iIyMIyxRFGXsy8/+/Lx3JEj52dPo6WD2sBgTB/8jua+ZTCMlkjxlL30wcdqpY6cSKqi63IKSQwBwfx6SyMAhQJ";
    private static String appId = "27";
    //        private static String privat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HLJjVzulF1MwCohj80EAvwKBgQDNsU9ZSKwZIspQxMueAyZwbsT6uqIECvOc3aQZixTtTQI2B36s+DJN8BEve2TBqXgIVbVXTepAsYuemRAc4JF0bumTgiY+oscn1YDYT3tHdLj7T7Z1ao6hN3yuccI8Xj0DeFy5lpLbaEI+VKv0svX87xWBdTwXNY7jgq1XhXF0iwKBgBeMpY/P9BUR+PL0a9FmIRByrOOTTm07wm29X0Apv4Se95f3stDk18ViClsLJEuaEsSJuRIgR215iONsSX4ivHxf+1Lq1D71R+wrDVVuDZgpVE/kmRD3+csaD3tj8WBQYZaiPpXAebdsM7k9ssAsvkL+XeBp7NMET1bHwatjIyTjAoGBAJIMvOFTXOB35Efj0kc9ugWTuPhvjTiBl1yXHDgbL9kvGTRLI2urFnDf71ytHqk8mIrUX/2y3/RM2/G4DE7AHZq9zr+oexvhzbC5/GCIAbRav+sNUeQuI/ekMUmvavayXxEDKNlsKDbqeKIJHYLtGinNDoUrjDBLwxoG67/1dBfr";
//    private static String appId = "15";
    private static String id = "18539428352";
    private static String url = "http://128.0.18.63:8080/openapi/";

    //    private static String lcslid = "1094e5a7a4c644f58d6f202d0b5615ff";
    private static String lcslid = "1f7e7869d75747278eb0f4db65ab4c85";


    public static void main(String[] args) {
        /*
        push();
        batchSign();
        expire();
        getUserCert();
        */
//        expire();
//        getqmz();
        getqmtp();
        try {
            String s = DigestUtils.md5Hex(new FileInputStream("D:\\DATA\\Pictures\\头像\\下载.jpg"));
            String s1 = DigestUtils.md5Hex(new FileInputStream("D:\\DATA\\Pictures\\头像\\下载 (1).jpg"));

            System.out.println(s);
            System.out.println(s1);
            System.out.println(s.equals(s1));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取用户证书
     */
    public static void getUserCert2() {
        try {
            // 组织请求数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("appId", appId);
            map.put("id", id);
            // 对msg做签名
            String indata = "appId=" + appId + "&id=" + id;
            byte[] signData = signature(privatekey, indata);
            String sign = new String(Base64.encode(signData));
            map.put("sign", URLEncoder.encode(sign, "UTF-8"));

            System.out.println("map=" + map.toString());
            String resp = HttpUtil.post(url + "/v1/user/cert", map);
            System.out.println("response == " + URLDecoder.decode(resp, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 推送签名
     */
    public static void push() {
        String bizSn = "488cf272-36f9-4037-ba61-d9fe348ac0a2";
        String inData = "患者：李四，年龄：30岁，科室：骨科，预约号：18，日期：2019-12-30";
        String callback_url = "http://127.0.0.1/";
        String mode = "redirect";
        String desc = "test";
        try {
            // 原文SHA256摘要处理
            String msg = GetSHA256FormString(inData);
            // 组织请求数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("appId", appId);
            map.put("id", id);
            map.put("bizSn", bizSn);
            map.put("msg", URLEncoder.encode(msg, "UTF-8"));
            map.put("url", URLEncoder.encode(callback_url, "UTF-8"));
            map.put("mode", mode);
            map.put("desc", URLEncoder.encode(desc, "UTF-8"));

            // 对msg做签名
            byte[] signData = signature(privatekey, msg);
            String sign = new String(Base64.encode(signData));
            map.put("sign", URLEncoder.encode(sign, "UTF-8"));

            System.out.println("request: " + map.toString());
            String resp = HttpUtil.post(url + "/v1/push/sign", map);
            System.out.println("response == " + URLDecoder.decode(resp, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量推送签名
     */
    public static void batchSign() {
        String bizSn = "488cf272-36f9-4037-ba61-d9fe348ac0a2";
        String inData = "患者：李四，年龄：30岁，科室：骨科，预约号：18，日期：2019-12-30";
        try {
            // 原文SHA256摘要处理
            String msg = GetSHA256FormString(inData);
            // 组织请求数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("appId", appId);
            map.put("id", id);

            JSONArray data = new JSONArray();
            JSONObject da = new JSONObject();
            da.put("bizSn", bizSn);
            da.put("msg", msg);
            da.put("msgWrapper", "0");
            da.put("desc", "123855522");
            data.add(da);

            map.put("data", URLEncoder.encode(data.toString(), "UTF-8"));

            // 对msg做签名
            byte[] signData = signature(privatekey, data.toString());
            String sign = new String(Base64.encode(signData));
            map.put("sign", URLEncoder.encode(sign, "UTF-8"));

            System.out.println("request: " + map.toString());
            String resp = HttpUtil.post(url + "/v1/batch/sign", map);
            System.out.println("response == " + URLDecoder.decode(resp, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取用户证书
     */
    public static void getUserCert() {
        try {
            // 组织请求数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("appId", appId);
            map.put("id", id);
            // 对msg做签名
            String indata = "appId=" + appId + "&id=" + id;
            byte[] signData = signature(privatekey, indata);
            String sign = new String(Base64.encode(signData));
            map.put("sign", URLEncoder.encode(sign, "UTF-8"));

            System.out.println("map=" + map.toString());
            String resp = HttpUtil.post(url + "/v1/user/cert", map);
            System.out.println("response == " + URLDecoder.decode(resp, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取用户印章
     */
    public static void getUserSeal() {
        try {
            // 组织请求数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("appId", appId);
            map.put("id", id);
            // 对msg做签名
            String indata = "appId=" + appId + "&id=" + id;
            byte[] signData = signature(privatekey, indata);
            String sign = new String(Base64.encode(signData));
            map.put("sign", URLEncoder.encode(sign, "UTF-8"));

            System.out.println("map=" + map.toString());
            String resp = HttpUtil.post(url + "/v1/user/seal", map);
            System.out.println("response == " + URLDecoder.decode(resp, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取免密时间
     */
    public static void expire() {
        try {
            // 组织请求数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("appId", appId);
            map.put("id", id);
            // 对msg做签名
            String indata = "appId=" + appId + "&id=" + id;
            byte[] signData = signature(privatekey, indata);
            String sign = new String(Base64.encode(signData));
            map.put("sign", URLEncoder.encode(sign, "UTF-8"));

            System.out.println("map=" + map.toString());
            String resp = HttpUtil.post(url + "/v1/user/expire", map);
            System.out.println("response == " + URLDecoder.decode(resp, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取用户签名值
     */
    public static void getqmz() {
        try {
            // 组织请求数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("appId", appId);
            // 对msg做签名
            String indata = "appId=" + appId + "&bizSn=" + lcslid;
            byte[] signData = signature(privatekey, indata);
            String sign = new String(Base64.encode(signData));
            map.put("sign", URLEncoder.encode(sign, "UTF-8"));

            System.out.println("map=" + map.toString());
            String resp = HttpUtil.post(url + "/v1/sign/info/" + lcslid, map);
            System.out.println(resp);
            System.out.println("response == " + URLDecoder.decode(resp, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取用户签名图片
     */
    public static void getqmtp() {
        try {
            // 组织请求数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("appId", appId);
            map.put("id", id);
            // 对msg做签名
            String indata = "appId=" + appId + "&id=" + id;
            byte[] signData = signature(privatekey, indata);
            String sign = new String(Base64.encode(signData));
            map.put("sign", URLEncoder.encode(sign, "UTF-8"));

            System.out.println("map=" + map.toString());
            String resp = HttpUtil.post(url + "/v1/user/seal", map);
            System.out.println(resp);
            System.out.println("response == " + URLDecoder.decode(resp, "UTF-8"));

            JSONObject jsonObject = JSON.parseObject(resp);
            JSONObject data = jsonObject.getJSONObject("data");
            String res = data.getString("seal");
            System.out.println(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static byte[] signature(String privateKey, String data) {
        try {
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyFactory.generatePrivate(keySpec);

            Signature oSig = Signature.getInstance(SIGN_ALGORITHMS);
            oSig.initSign(priKey);
            oSig.update(data.getBytes("UTF-8"));
            return oSig.sign();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String GetSHA256FormString(String inData) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] messageDigest = md.digest(inData.getBytes());
            result = new String(BASE64EncoderStream.encode(messageDigest));
            System.out.println("BASE64EncoderStream1: " + result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
}
